package cn.sisyphe.framework.auth.logic;


import cn.sisyphe.framework.web.exception.AccessDeniedException;

import java.util.Set;

/**
 * Created by heyong on 2017/11/23 16:41
 * Description: 权限范围认证
 *
 * @author heyong
 */
public class ScopeAuthenticationAdapter {

    private final String ALL_SCOPE = "ALL";
    private AuthenticationSupplier supplier;

    public ScopeAuthenticationAdapter(AuthenticationSupplier supplier) {
        this.supplier = supplier;
    }

    /**
     * 验证权限范围
     * @param token
     * @param requestScope
     * @return
     * @throws AccessDeniedException
     */
    public Set<String> identifyPermissionScope(String token, Set<String> requestScope) throws AccessDeniedException {
        Set<String> authorizeScope = supplier.findScope(token);

        if (authorizeScope == null) {
            return null;
        } else if (authorizeScope.contains(ALL_SCOPE)) {
            // 如果是全开放则返回请求范围
            return requestScope;
        } else if (requestScope == null) {
            return null;
        }

        // 移除不同的元素
        requestScope.retainAll(authorizeScope);

        return requestScope;
    }
}
